<template>
  <div class="users-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="params.query"  clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
     
      <el-table
        :data="userList"
        border
        style="width: 100%">
        <el-table-column
          type="index"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="用户权限">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <el-switch @change="changeState(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip :enterable="false" class="item" effect="dark" content="分配权限" placement="top">
              <el-button type="success" icon="el-icon-share" size="mini" @click="showRightsDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible" @close="addResetForm('addRuleForm')">
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addRuleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addRuleForm.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmitForm('addRuleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editRuleForm" :rules="editRules" ref="editRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="editRuleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editRuleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editRuleForm.email"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEditDialog('editRuleForm')">取 消</el-button>
        <el-button type="primary" @click="editFormSubmit('editRuleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="rightsDialogVisible"
      width="45%">
      <el-form label-position="right" label-width="80px">
        <el-form-item label="用户名:" >
          {{rightsObj.username}}
        </el-form-item>
        <el-form-item label="邮箱:">
          {{rightsObj.email}}
        </el-form-item>
        <el-form-item label="当前权限:">
          {{rightsObj.role_name}}
        </el-form-item>
        <el-form-item label="分配权限:">
          <el-select v-model="rightsID" placeholder="请选择权限">
            <el-option
              v-for="item in allotList"
              :key="item.id"
              :label="item.roleName" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkEmail = (rule, value, cb) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/

      if( reg.test(value) ) {
        return cb()
      }

      cb(new Error('邮箱格式错误，请填写正确邮箱格式'))
    }

    const checkMobile = (rule, value, cb) => {
      const reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/

      if( reg.test(value) ) {
        return cb()
      }

      cb(new Error('手机格式错误，请填写正确手机格式'))
    }

    return {
      rightsDialogVisible: false,
      rightsObj: {},
      addRuleForm: {
        username: '',
        email: '',
        mobile: '',
        password: ''
      },
      editRuleForm: {
        username: '',
        email: '',
        mobile: '',
        password: ''
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱名称', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      editRules: {
        email: [
          { required: true, message: '请输入邮箱名称', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      params: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      total: 0,
      userList: [],
      allotList: [],
      rightsID: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('/users', {
        params: this.params
      })

      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.total = res.data.total
      this.userList = res.data.users
    },
    handleSizeChange(val) {
      this.params.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.params.pagenum = val
      this.getUserList()
    },
    async changeState(row) {
      const {id, mg_state} = row

      const {data: res} = await this.$http.put(`users/${id}/state/${mg_state}`)

      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.$message({
        showClose: true,
        message: res.meta.msg,
        type: 'success'
      })
    },
    addResetForm(formName) {
      this.$refs[formName].resetFields()
    },
    addSubmitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if(!valid) {
          return false
        }

        const {data: res} = await this.$http.post(`users`, this.addRuleForm)

        if(res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.addDialogFormVisible = false
      })
    },
    async showEditDialog(id) {
      const {data: res} = await this.$http.get(`users/${id}`)

      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.editRuleForm = res.data
      this.editDialogFormVisible = true
    },
    cancelEditDialog(formName) {
      this.$refs[formName].resetFields()
      this.editDialogFormVisible = false
    },
    editFormSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if(!valid) {
          return false
        }

        const {data: res} = await this.$http.put(`users/${this.editRuleForm.id }`, this.editRuleForm)

        if(res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        }
        
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.editDialogFormVisible = false
      })
    },
    deleteUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await this.$http.delete(`users/${id}`)

        if(res.meta.status !== 200) {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })      
      })
    },
    async showRightsDialog(row) {
      this.rightsObj = row

      const {data: res} = await this.$http.get('roles')

      this.allotList = res.data

      this.rightsDialogVisible = true
    },
    async saveUserRights() {
      const {data} = await this.$http.put(`users/${this.rightsObj.id}/role`, {rid: this.rightsID})

      if(data.meta.status !== 200) {
        return 
      }

      this.$message.success(data.meta.msg)
      this.getUserList()
      this.rightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.users-container {
  .el-card{
    margin-top: 20px;
  }
  .el-table{
    margin: 20px 0;
  }
}
</style>
